/*
 * Label.cpp
 *
 *  Created on: 18.2.2013
 *      Author: Travis
 */

#ifdef _WIN32 
#include <windows.h> 
#endif

#include "Button.h"

namespace Gadgets
{

Button::Button(int _width, int _height) :
		Form(_width, _height)
{
	caption = "";

	text = new glFont(Engine::fontSettings.fontFile);
	text->BuildFont();

	click = false;
}

Button::~Button()
{
}

void Button::draw()
{
	int addsize;

	if (visible)
	{
		addsize = 0;

		if ((mouseInside) && (!click))
			addsize = MARKED_SIZE;
		else if (click)
		{
			addsize = CLICK_SIZE;
		}

		if (background != NULL)
			if (root != NULL)
				background->draw(root->getPos() + Pos, addsize);
			else
				background->draw(Pos, addsize);

		if (root != NULL)
			text->glPrint(root->getPos().x + Pos.x, root->getPos().y + Pos.y, 0,
					caption.c_str());
		else
			text->glPrint(Pos.x, Pos.y, 0, caption.c_str());
	}

	click = false;
}

void Button::control(SDL_Event *event)
{
	int mx, my;

	if (visible)
	{
		SDL_GetMouseState(&mx, &my);

		MouseOver(event, mx, my);
	}
}

void Button::MouseOver(SDL_Event *event, int x, int y)
{
	glm::vec2 posBuf;

	if (root != NULL)
		posBuf = root->getPos() + Pos;
	else
		posBuf = Pos;

	DataTypes::Rectangle2D rec(glm::vec2(posBuf.x, posBuf.y + height),
			glm::vec2(posBuf.x, posBuf.y), glm::vec2(posBuf.x + width, posBuf.y),
			glm::vec2(posBuf.x + width, posBuf.y + height));

	if (rec.pointInRectangle2D(glm::vec2(x, y)))
	{
		// push mouse over event
		MouseOverEvent.user.code = FORM_EVENT_MOUSE_OVER;

		if (!mouseInside)
		{
			SDL_PushEvent(&MouseOverEvent);
			mouseInside = true;
		}

		// check click
		MouseClick(event);

		for (unsigned int i = 0; i < items.size(); i++)
			if (items[i] != NULL)
				items[i]->MouseOver(event, x, y);
	}
	else
		setMouseInside(false);
}

void Button::MouseClick(SDL_Event *event)
{
	// mouse button click
	if (event->type == SDL_MOUSEBUTTONDOWN)
	{
		// left mouse button click
		if (event->button.button == (SDL_BUTTON_LEFT))
		{
			// push mouse left click event
			MouseOverEvent.user.code = FORM_EVENT_MOUSE_CLICK_LEFT;
			SDL_PushEvent(&MouseOverEvent);
			click = true;
		}

		if (event->button.button == (SDL_BUTTON_RIGHT))
		{
			// push mouse left click event
			MouseOverEvent.user.code = FORM_EVENT_MOUSE_CLICK_RIGHT;
			SDL_PushEvent(&MouseOverEvent);
		}
	}
}

const std::string& Button::getCaption() const
{
	return caption;
}

void Button::setCaption(const std::string& caption)
{
	this->caption = caption;
}

} /* namespace Gadgets */
